package net.bat.web.xggrzl;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import net.bat.entity.User;

@Component
@Transactional
public class UpdatePersonService {
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;
	private static Logger logger = LoggerFactory.getLogger(UpdatePersonService.class);
	@Autowired
	private UpdatePersonDao updao;
	/**
	 * 按照登录名查询
	 * @param loginName
	 * @return 对象
	 */
	public User findUserByLoginName(String loginName) {
		return updao.findByLoginName(loginName);
		}
	/**
	 * 按照ID查询
	 * @param id
	 * @return
	 */
	public User getUser(Long id) {
		return updao.findOne(id);
	}
	public void updateUserInfo(User user){
		if(StringUtils.isNotBlank(user.getPassword())){
			entryptPassword(user);
		}
		updao.equals(user);
	}
	/**
	 * 设定安全的密码，生成随机的salt并经过1024次 sha-1 hash
	 */
	
	private void entryptPassword(User user) {
	
			byte[] salt = Digests.generateSalt(SALT_SIZE);
			user.setSalt(Encodes.encodeHex(salt));
			byte[] hashPassword = Digests.sha1(user.getPlainPassword().getBytes(), salt, HASH_INTERATIONS);
		   
			user.setPassword(Encodes.encodeHex(hashPassword));
				
	}
	/**
	 * 密码验证
	 * @param orgPassword
	 * @param salt
	 * @return
	 */
	public String checkPassword(String orgPassword,String salt){
		byte[] salt2 =Encodes.decodeHex(salt);		
		byte[] orgPassword2=Digests.sha1(orgPassword.getBytes(), salt2, HASH_INTERATIONS);
		String orgPassword22=Encodes.encodeHex(orgPassword2);
		
		return orgPassword22;
			
	}	
	
}
